package com.lottery.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lottery.api.service.OrderInfoApiService;
import com.lottery.common.contants.Constants;
import com.lottery.common.contants.ReQueryResult;
import com.lottery.common.contants.SequenceConstants;
import com.lottery.common.dao.EventsInfoMapper;
import com.lottery.common.dao.MemberInfoMapper;
import com.lottery.common.dao.OrderInfoMapper;
import com.lottery.common.entity.*;
import com.lottery.common.service.OrderInfoService;
import com.lottery.common.service.SequenceService;
import com.lottery.common.utils.RedisUtils;
import com.lottery.pay.Constants.PaymentConstant;
import com.lottery.pay.service.PaymentRecordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

import static com.lottery.common.contants.Constants.*;

/**
 * <p>
 * 订单信息表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-09-23
 */
@Service
@Slf4j
public class OrderInfoApiServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoApiService {
    private ReQueryResult result = new ReQueryResult();
    @Resource
    private MemberInfoMapper memberInfoMapper;
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private EventsInfoMapper eventsInfoMapper;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private PaymentRecordsService paymentRecordsService;

    /**
     * 创建订单 默认订单状态为待支付
     * 根据订单类型  除了余额介为后台查询金额。
     * @param orderInfo
     * @return
     */
    @Override
    public ReQueryResult createOrder(OrderInfo orderInfo, HttpServletRequest request) {
        result = new ReQueryResult();
        orderInfo.setStatus(TYPE_TWO);
        orderInfo.setTitle(RedisUtils.getConfigFromRedis("050"+orderInfo.getOrderType(), SysConfig.class).getValue());
        if (orderInfo.getOrderType()==TYPE_ONE){
            EventsInfo eventsInfo=eventsInfoMapper.selectById(orderInfo.getTypeValue());
            orderInfo.setAmount(eventsInfo.getPrice());
        }
        if ( orderInfo.getOrderType()==TYPE_TWO){
            String [] str=orderInfo.getTypeValue().split(",");
            BigDecimal b=new BigDecimal(0);
            for(String s:str){
                b=b.add(new BigDecimal(RedisUtils.getConfigFromRedis(s, SysConfig.class).getValue()));
            }
            orderInfo.setAmount(b);
        }
        //购买会员
        if (orderInfo.getOrderType()==TYPE_THREE){
            SysConfig sysConfig=RedisUtils.getConfigFromRedis(orderInfo.getTypeValue(), SysConfig.class);
            NutMap nutMap= JSON.parseObject(sysConfig.getValue(),NutMap.class);
            orderInfo.setAmount(new BigDecimal(nutMap.getString("value")));
        }
        orderInfo.setOrderNum(sequenceService.getSequenceByName(SequenceConstants.SEQUENCE_ORDER_ID).toString());
        Integer ocount=orderInfoMapper.insert(orderInfo);
        log.info("订单创建 {}",ocount);

        if (ocount<=0){
            result.error(ORDER_ERROR);
            return result;
        }

        PaymentRecords records = new PaymentRecords(orderInfo.getPayType(),orderInfo.getTradeType(),orderInfo.getOrderNum(),orderInfo.getAmount(),TYPE_ONE);
        records.setBody(orderInfo.getTitle());
        records.setMemberId(orderInfo.getMemberId());
        boolean flag=paymentRecordsService.save(records);
        log.info("支付订单创建 {}",flag);
        if (!flag){
            result.error(PaymentConstant.PAY_ORDER_ERROR);
            return result;
        }
        result=paymentRecord(records,orderInfo,request);
        return result;
    }

    @Override
    public ReQueryResult paymentRecord(PaymentRecords records,OrderInfo orderInfo,  HttpServletRequest request) {
        result = new ReQueryResult();

        String ip = request.getHeader("X-FORWARDED-FOR");
        if (com.alibaba.druid.util.StringUtils.isEmpty(ip)) {
            ip = request.getRemoteAddr();
        }
        ip=ip.split(",")[0];
        log.info("ip is {}",ip);
        records.setIp(ip);

        try {
            result=paymentRecordsService.payAll(records);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.error(ExceptionUtils.getFullStackTrace(e));
            result.error(Constants.INSIDE_WRONG_DESC);
            return result;
        }

        return result;
    }






}
